package com.sun.controller;

import ch.qos.logback.core.util.TimeUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.UUID;

@Controller
public class FileController {

    @GetMapping(value = "/file")
    public String file(){
        return "file";
    }

    @PostMapping(value = "/fileUpload")
    public String fileUpload(@RequestParam(value = "file")MultipartFile file,
                             Model model, HttpServletRequest request) throws IOException {
        if (file.isEmpty()){
            System.out.println("文件为空");
        }
        String fileName = file.getOriginalFilename();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmm");

        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID() +simpleDateFormat.format(new Date())+ suffixName;//新文件名
        String filePath = "../img/";//上传后的路径
        File dest = new File(filePath+fileName);
        System.out.println(dest.getAbsolutePath());
        if(!dest.exists()){
            dest.createNewFile();
        }
        dest = new File(dest.getAbsolutePath());
        file.transferTo(dest);
        model.addAttribute("filename",dest.getAbsolutePath());
        return "picture";
    }
    @PostMapping(value = "/upload")
    @ResponseBody
    public void upload(@RequestParam MultipartFile multipartFile) throws IOException {
        String fileName = multipartFile.getOriginalFilename();

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmm");
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID() +simpleDateFormat.format(new Date())+ suffixName;//新文件名
        String filePath = "../img/";//上传后的路径
        File dest = new File(filePath+fileName);
        System.out.println(dest.getAbsolutePath());
        if(!dest.exists()){
            dest.createNewFile();
        }
        dest = new File(dest.getAbsolutePath());
        multipartFile.transferTo(dest);
    }
}
